<?php
namespace lib\wxbiz;

use common\models\WxbizMenu;

class Menu
{

    public static function Publish($agent_id)
    {
        $button = [];
        $menus = WxbizMenu::find()->where([
            'agent_id' => $agent_id
        ])
            ->asArray()
            ->all();
        foreach ($menus as $key => $value) {
            $menu = [
                'type' => $value['type'],
                'name' => $value['name'],
                'key' => $value['key'],
                'url' => $value['url']
            ];
            if ($value['pid'] == 0) {
                $button[$value['id']] = $menu;
            } else {
                $button[$value['pid']]['sub_button'][] = $menu;
            }
        }
        $data = [
            'button' => array_values($button)
        ];
        $access_token = WechatCache::getAccessToken($agent_id);
        $agentid = WechatCache::getAgentid($agent_id);
        if ($agentid == 1) {
            return [
                'errcode' => -1,
                'errmsg' => '公司通讯录不能设置自定义菜单'
            ];
        }
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/menu/create?access_token=' . $access_token . '&agentid=' . $agentid;
        return Curl::callWebServer($url, json_encode($data, JSON_UNESCAPED_UNICODE), 'POST');
    }

    /**
     *
     * @param integer $id            
     * @example $menu = Menu::getMenu(1);<br>var_dump($menu);
     */
    public static function getMenu($id)
    {
        $access_token = WechatCache::getAccessToken($id);
        $agentid = WechatCache::getAgentid($id);
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/menu/get?access_token=' . $access_token . '&agentid=' . $agentid;
        return Curl::callWebServer($url, '', 'GET');
    }

    /**
     *
     * @param integer $id            
     * @return 成功 {"errcode":0,"errmsg":"ok"}
     *         失败 {"errcode":0,"errmsg":"ok"}
     */
    public static function delMenu($id)
    {
        $access_token = WechatCache::getAccessToken($id);
        $agentid = WechatCache::getAgentid($id);
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/menu/delete?access_token=' . $access_token . '&agentid=' . $agentid;
        return Curl::callWebServer($url, '', 'GET');
    }
}